package com.googlecode.perfectable.visuable.webchat.ui;

import static com.google.common.base.Preconditions.checkNotNull;

import com.googlecode.perfectable.eventable.routing.Router;
import com.googlecode.perfectable.eventable.routing.Sink;
import com.googlecode.perfectable.visuable.visual.ParentVisual;
import com.googlecode.perfectable.visuable.visual.StandardVisual;
import com.googlecode.perfectable.visuable.visual.StandardVisual.ElementVisualBuilder;
import com.googlecode.perfectable.visuable.visual.controller.Controller;
import com.googlecode.perfectable.webchat.ChatService;
import com.googlecode.perfectable.webchat.Message;
import com.googlecode.perfectable.webchat.Message.Writer;

public class MessageListController implements Controller<ParentVisual> {
	private static final class MessageWritingSink implements Sink<Message> {

		static class VisualWriter implements Writer {
			final ElementVisualBuilder builder = StandardVisual.builder("li");

			@Override
			public void writeBody(String body) {
				this.builder.withTextPart(body);
			}

			void flush(ParentVisual appended) {
				StandardVisual messageVisual = this.builder.build();
				appended.append(messageVisual);
			}
		}

		private final ParentVisual appended;

		public MessageWritingSink(ParentVisual appended) {
			this.appended = appended;
		}

		@Override
		public void receive(Message message) {
			final VisualWriter writer = new VisualWriter();
			message.write(writer);
			writer.flush(this.appended);
		}
	}

	private final Router<Message> buffer = Router.create();

	@Override
	public void takeControl(ParentVisual visual) {
		checkNotNull(visual);
		final Sink<Message> listener = new MessageWritingSink(visual);
		this.buffer.route(listener);
	}

	public void setChatService(ChatService chatService) {
		checkNotNull(chatService);
		chatService.listen(this.buffer);
	}

}
